package com.csnf.servlet;

import com.csnf.dao.AuthorDao;
import com.csnf.entity.Authors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/authorServlet")
public class AuthorServlet extends HttpServlet {
    AuthorDao authorDao = new AuthorDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if(action==null){
            getAll(req, resp);
        }else{
            switch (action){
                case "detail":
                    detailAuthor(req, resp);
                    break;
                case "delete":
//                deleteAuthor(req, resp);
                    break;
                default:
                    getAll(req, resp);
            }
        }

    }

    private void detailAuthor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String authorId = req.getParameter("authorId");
        try {
            Authors author = authorDao.getAuthorById(Integer.parseInt(authorId));
            req.setAttribute("author", author);
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.getRequestDispatcher("authorDetail.jsp").forward(req, resp);
    }

    private void getAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Authors> authorsList = authorDao.getAuthorsList();
            req.setAttribute("authorsList", authorsList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        req.getRequestDispatcher("authorList.jsp").forward(req, resp);
    }
}
